var defaultImgSrc = "https://imgsrv1.mailer08.net/images/dGVuYW50Mjg3YWRtaW4_/WTJGdGNHRnBaMjVmTWpJPQ/coupons_20180528_1.jpg"
var today = +new Date();
var lang = "_c",relang = "";
var redeemUrl = redeemUrl; // 此变量来自views/member-binding/couponlist.php
var codelist = {};
var termsList = {};
function isDateValid(date) {
    if (!!date)
        return !isNaN(+new Date(date.replace(/-/g, "/")))
}

var ImgUrlList=['../../jselect/img/active_2.png','../../jselect/img/active_1.png','../../jselect/img/active_3.png'];
var ImgUrlList2=['../../jselect/img/expired_2.png','../../jselect/img/expired_1.png','../../jselect/img/expired_3.png'];

function classify(obj) { //根據卡券類型和日期狀態展示不同的日期
    var data = obj || {};
    var couponStatus = data.status || 1;
    var status = '';
    var n1 = '', n2 = '';
    var n3 = '';
    var n4 = '';
    var n5 = '';
    var result = "";
    var validHtml = '';
    var end = 253370764800000;
   
    if (isDateValid(data.startdate)) {
        n1 = data.startdate.substr(0, 10)
    }
    if (isDateValid(data.enddate)) {
        n2 = data.enddate.substr(0, 10)
        end = +new Date(data.enddate.replace(/-/g, "/"));
    } else {
        end = 253370764800000
        n2 = ''
    }
    if (isDateValid(data.useddate)) {
        n3 = data.useddate.substr(0, 10)
    }
    if (isDateValid(data.createtime)) {
        n4 = data.createtime.substr(0, 10)
    }
    if (isDateValid(data.acceptedtime)) {
        n5 = data.acceptedtime.substr(0, 10)
    }
    
    if (n1 && n2) { //開始結束都在
        if (n1 == n2) {//且相同
            validHtml += "Valid only on " + n1
        }
    }
    if (n1 && !n2) {//開始在
//        validHtml += "开始日期: " + n1
        validHtml += "长期有效"
    }
    if (n2) {//結束在
        validHtml += "截止日期: " + n2
    }
    if (couponStatus == 1 && (n2 || n1)) {
        status = "valid"
        result += '  		<div class="validDate">' + validHtml + '</div>'
    }
    if (couponStatus == 2 && n3) {
        status = "used"
        var store_id = data.store_id ? ("<br>Redeem by:" + data.store_id) : '';
        // if (data.store_id) {
        //     result += '  		<div class="validDate">' + data.store_id + '</div>'
        // }
        result += '  		<div class="validDate">核销时间: ' + n3 + '</div>'
    }
    if (couponStatus == 3 && n4) {
        status = "used"
        result += '  		<div class="validDate">sharing on: ' + n4 + '</div>'
    }
    if (couponStatus == 4 && n5) {
        status = "valid"
        result += '  		<div class="validDate">accepted on: ' + n5 + '</div>'
    }
    if (couponStatus == 1 && today > end) {
        status = "expired"
        result = '  		<div class="validDate">已过期</div>'
    }
    return { result: result, status: status }
}

function createCoupon(obj) {
	
    var valid_html = '<ul class="coupnsList">'
    var used_html = '<ul class="coupnsList">'
    var expired_html = '<ul class="coupnsList">'
    var valid_count = 0
    var used_count = 0
    var expired_count = 0
    $.each(obj, function (k, val) {
        var result = classify(val)
        var html = '';
        var couponInfo = val.coupon_info;
        var description = couponInfo["description" + lang] ? couponInfo["description" + lang]
            : couponInfo["description" + relang] ? couponInfo["description" + relang] : '';
        var conditions = couponInfo["conditions" + lang] ? couponInfo["conditions" + lang]
            : couponInfo["conditions" + relang] ? couponInfo["conditions" + relang] : '无限制卡券!';
        var name = couponInfo["name" + lang] ? couponInfo["name" + lang]
            : couponInfo["name" + relang] ? couponInfo["name" + relang] : '';
        var terms = couponInfo.terms
            if(terms){
                terms = '<li>'+terms.split('\n').join('</li><li>')+'</li>'
            }
        var couponImgUrl = couponInfo.thumbnail_url ? couponInfo.thumbnail_url :defaultImgSrc;
        var baseURL='../../jselect/img/';
        var ImgUrl1=(couponInfo["name"]=="￥100")?'active_2.png':(couponInfo["name"]=="九折券")?'active_1.png':'active_3.png';
        var ImgUrl2 =(couponInfo["name"]=="￥100")?'expired_2.png':(couponInfo["name"]=="九折券")?'expired_1.png':'expired_3.png';
       
        var coupon_code = val.coupon_code
        var className = '';
        var couponImgUrl='';
        var fontClass='';
         //result.status="expired";
        if (result.status == "valid") {
            className="canUseBack"
            couponImgUrl=baseURL+ImgUrl1;
        }
        if (result.status == "used") {
            className="usedBack"
            couponImgUrl=baseURL+ImgUrl2;
            fontClass="grey";
        }
        if (result.status == "expired") { 
            className="expiredBack"
            couponImgUrl=baseURL+ImgUrl2;
            fontClass="grey";
        }
        var text=''
        if(couponInfo.coupon_type == 'text'){
            text += '<div class="weui-flex desc">'+
                        '<div class="weui-flex-item flex f16 hasicon"><span class="icon icon-97 icon-text coupon_icon"></span>'+couponInfo.description+'</div>'+
                        '<div class="weui-flex-item">礼品券</div>'+
                    '</div>'
        }
        if(couponInfo.coupon_type == 'cash'){
            text += '<div class="weui-flex desc">'+
                        '<div class="weui-flex-item flex">&yen; <span class="f40">'+couponInfo.description+'</span></div>'+
                        '<div class="weui-flex-item">现金券</div>'+
                    '</div>'
        }
        if(couponInfo.coupon_type == 'discount'){
            text += '<div class="weui-flex desc">'+
                        '<div class="weui-flex-item flex"><span class="f40">'+couponInfo.description+'</span> %</div>'+
                        '<div class="weui-flex-item">折扣券</div>'+
                    '</div>'
        }
        if(couponInfo.coupon_type == 'ty'){
            text += '<div class="weui-flex desc">'+
            			'<div class="weui-flex-item flex f16 hasicon" style="word-break:keep-all;"><span class="icon icon-27 icon-text coupon_icon"></span>'+couponInfo.description+'</div>'+
                        '<div class="weui-flex-item">体验券</div>'+
                    '</div>'
        }
        var downIcon = result.status == "valid"?'<span class="icon icon-35 "></span>':'';
        html += '<li class="weui_cells couponBox">                                          ' +
            '    <div class="weui_cell couponCard js-category '+className+'">' +
           
            '        <div class="weui_cell_bd weui_cell_primary couponLogo">' +text+
            // '            <img src="' + couponImgUrl + '"' +
            // '            class="img-max"> ' +
            '           <div class="dateBox">'+result.result+downIcon+
            '</div>'+
            
            '        </div>' +
            '        <div class="middleDiv"> ' +
            '            <div class="ltop"></div> ' +
            '           <div class="lmiddle"></div> ' +
            '           <div class="lbottom"></div> ' +
            '        </div> ' +
            '        <div class="weui_cell tcenter couponInfo">' +
            // '            <div>'+name+'</div>' +
            '            <div>'+couponInfo.description_c+'</div>' ;
        
        html +=  result.status == "valid"?'<button class="weui_btn weui_btn_mini weui_btn_default redeemBtn js-propShow '+fontClass+'" data-coupon_code="' + coupon_code + '">核 销</button>':'';
       
        html +='       </div>' +
            '          <div class="rightBorder"></div>'+
            '    </div>' ;
            var couponTnc='    <div class="page-category js-categoryInner couponTnc">' +
                '        <div class="weui_cells" style="margin-top: 0px;">' +
                '            <div class="weui_cell">' +
                '                <div class="weui_cell_bd weui_cell_primary barcodecontainer">' +
                '                    <div class="tcenter"><img id="code'+val.id+'" class="barcode"></div>'+
                '                    <p class="f-j tnc js-propShow1" data-id="'+val.id+'"><u>使用条款及细则</u></p>' +
                '                </div>' +
                '            </div>   ' +
                '        </div>' +
                '    </div>' ;
        html +=  result.status == "valid" ? couponTnc:'';   
        html +=  '</li>'
        if (result.status == "valid") {
            valid_html += html;
            valid_count++;
            termsList[val.id] = terms
            codelist[val.id] = val.coupon_code
            if(val.coupon_info.barcode_pattern !='' && val.coupon_info.barcode_pattern !=undefined){//臨時解決方案20180726
                codelist[val.id] = val.coupon_info.barcode_pattern.fixed_value
            }
        }
        if (result.status == "used") {
            used_html += html;
            used_count++
        }
        if (result.status == "expired") {
            expired_html += html;
            expired_count++
        }
    })
    var nocoupon = '<li class="tcenter" style="font-size:16px">您没有该类卡券!</li>'
    valid_count == 0 ? valid_html += nocoupon + '</ul>' : valid_html += '</ul>';
    used_count == 0 ? used_html += nocoupon + '</ul>' : used_html += '</ul>';
    expired_count == 0 ? expired_html += nocoupon + '</ul>' : expired_html += '</ul>';

    return { valid_html, used_html, expired_html }
}
function barcode(id,code){
    JsBarcode(id,code, {
        format: "CODE128",//选择要使用的条形码类型
        width:3,//设置条之间的宽度
        height:50,//高度
        displayValue:true,//是否在条形码下方显示文字
        // text:"456",//覆盖显示的文本
        fontOptions:"bold",//使文字加粗体或变斜体
        // font:"fantasy",//设置文本的字体
        textAlign:"center",//设置文本的水平对齐方式
        textPosition:"bottom",//设置文本的垂直位置
        textMargin:5,//设置条形码和文本之间的间距
        fontSize:20,//设置文本的大小
        background:"#fff",//设置条形码的背景
        lineColor:"#000",//设置条和文本的颜色。
        margin:15//设置条形码周围的空白边距
      });
}

$(function () {
    var result = createCoupon(data);
    $("#validCoupon").html(result.valid_html)
    $("#usedCoupon").html(result.used_html)
    $("#expiredCoupon").html(result.expired_html)
    $.each(codelist,function(k,v){
        barcode("#code"+k,v)
        // barcode("#code"+k,'000028')
    })
    var coupon_code = '';

    $("#topTab").tab({ defaultIndex: 0, activeClass: "tab-blue" }).on("click", ".weui_navbar_item", function () {
        var activeTabIndex = $(this).index()
        $(".tab_content").removeClass("active").eq(activeTabIndex).addClass("active")
    });
    $(".js-propShow").click(function (e) {
        coupon_code = '';
        coupon_code = $(this).attr("data-coupon_code")
        e.stopPropagation()
        showmark()
    })
    $(".js-propShow1").click(function (e) {
        e.stopPropagation()
        showmark1()
        var id = $(this).attr('data-id')
        $('.tncList').html(termsList[id])
    })
    $(".js-propHide").click(function () {
        hidemark()
        hidemark2()
    })
    function showmark() {
        $(".weui_mask").addClass("weui_mask_visible");
        $(".redeempop").addClass("weui-dialog-visible");
    }
    function hidemark() {
        $(".weui_mask").removeClass("weui_mask_visible");
        $(".redeempop").removeClass("weui-dialog-visible");
    }
    function showmark1() {
        $(".weui_mask").addClass("weui_mask_visible");
        $(".tncpop").addClass("weui-dialog-visible");
    }
    function hidemark2() {
        $(".weui_mask").removeClass("weui_mask_visible");
        $(".tncpop").removeClass("weui-dialog-visible");
    }
    $(".js-category").click(function () {
        $parent = $(this).parent("li");
        if ($parent.hasClass("js-show")) {
            $parent.removeClass("js-show");
            // $(this).children("i").removeClass("icon-35").addClass("icon-74");
        } else {
            $parent.siblings().removeClass("js-show");
            $parent.addClass("js-show");
            // $(this).children("i").removeClass("icon-74").addClass("icon-35");
            // $parent.siblings().find("i").removeClass("icon-35").addClass("icon-74");
        }
    });
    $(".js-redeemConfirm").click(function () {
        var _this = $(this);
        var redeem_password = $("#redeem_code").val();
        if (redeem_password.trim() == '') {
            $(".confirm_res_msg").addClass('f-red').html('请输入核销码')
            return
        }
        _this.attr("disabled", true);
        //console.log(redeemUrl);
        $.post(redeemUrl, { coupon_code: coupon_code, redeem_password: redeem_password }, function (re) {
            ////console.log(re);
            if (re.status == 'success') {
                _this.attr("disabled", true);
                $(".confirm_res_msg").removeClass('f-red').addClass("f-green").html('核销成功.<br>谢谢惠顾!')
                setTimeout(function () {
                    window.location.reload();
                }, 1000)
            } else {
                _this.removeAttr("disabled");
                var msg = re.message;
                if (msg.indexOf("rule") !== -1) {
                    msg = "同一组卡券只能核销一次!"
                } else {
                    msg = "核销码错误"
                }
                $(".confirm_res_msg").addClass('f-red').html(msg)
            }
        }, 'json');
    });
})
